import React, { useState, useEffect } from 'react';
import { connect } from 'umi';
import {
  Card,
  Typography,
  Skeleton,
  Row,
  Col,
  Tag,
  Select,
  Button,
  Modal,
  Table,
  notification,
  Space,
  Spin,
  message,
  Empty,
} from 'antd';
import type { ConnectState } from '@/models/connect';
import { PageContainer } from '@ant-design/pro-layout';
import { ExportOutlined, SearchOutlined } from '@ant-design/icons';
import { CurrentUser } from '../../../models/user';
import { utils as xlsxUtils, writeFile, WorkBook } from 'xlsx';
import {
  getSchoolYearsData,
  getTeacherTeachingEvaluationResult,
  getCollegesResult,
} from '@/services/service';

const { Title } = Typography;
const { Option } = Select;
interface IResultQueryInterface {
  user: CurrentUser;
}

export interface Item {
  key: string;
  courseName: string;
  number: number;
  studentEvaluate: number;
  supervisorEvaluate: number;
  teacherEvaluate: number;
}

type syntheticalEvaluateType = {
  average?: string;
  collegesRank?: string;
  evaluateResult?: string;
};

/**
 * @description 评教查询
 */
const ResultQuery: React.FC<IResultQueryInterface> = (props) => {
  const [semesters, setSemesters] = useState([]);
  const [semester, setSemester] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [schoolYear, setSchoolYear] = useState('');
  const [schoolYears, setSchoolYears] = useState([]);
  const [downloaded, setDownloaded] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [collegesResultData, setCollegesResultData] = useState([]);
  const [teachingEvaluationResult, setTeachingEvaluationResult] = useState([]);
  const [syntheticalEvaluate, setSyntheticalEvaluate] = useState<syntheticalEvaluateType>({});

  useEffect(() => {
    (async () => {
      // 获取学年以及学期数据
      const result: any = await getSchoolYearsData();
      setSchoolYears(result.schoolYears);
      setSemesters(result.semesters);
      setIsLoading(false);
    })();
  }, []);

  // 学期映射
  const semesterMap = {
    '1': '一',
    '2': '二',
    '3': '三',
    '4': '四',
    '5': '五',
  };

  // 教师和督导角色可以看到的表格的列
  const teacherColumns = [
    {
      title: '编号',
      dataIndex: 'number',
    },
    {
      title: '课程名称',
      dataIndex: 'courseName',
    },
    {
      title: '学生评价',
      dataIndex: 'studentEvaluate',
      sorter: {
        compare: (a: Item, b: Item) => {
          return a.studentEvaluate - b.studentEvaluate;
        },
        multiple: 3,
      },
    },
    {
      title: '同行互评',
      dataIndex: 'teacherEvaluate',
      sorter: {
        compare: (a: Item, b: Item) => a.teacherEvaluate - b.teacherEvaluate,
        multiple: 2,
      },
    },
    {
      title: '督导评价',
      dataIndex: 'supervisorEvaluate',
      sorter: {
        compare: (a: Item, b: Item) => a.supervisorEvaluate - b.supervisorEvaluate,
        multiple: 1,
      },
    },
  ];

  // 院系角色可以看到的表格的列
  const collegesColumns = [
    {
      title: '教师编号',
      dataIndex: 'userNumber',
      width: `${100 / 5}%`,
    },
    {
      title: '教师姓名',
      dataIndex: 'userName',
      width: `${100 / 5}%`,
    },
    {
      title: '综合评价分',
      dataIndex: 'syntheticalEvaluate',
      width: `${100 / 5}%`,
    },
    {
      title: '评价结果',
      dataIndex: 'evaluateResult',
      width: `${100 / 5}%`,
    },
    {
      title: '院系排名',
      dataIndex: 'collegesRank',
      width: `${100 / 5}%`,
    },
  ];

  // 续期数据格式化
  const formatSemester = (param: number) => {
    const keys = Object.keys(semesterMap);
    const temp = keys.filter((item) => Number(item) === param);
    return `第${semesterMap[temp[0]]}学期`;
  };
  // 渲染教师和督导角色才能看见的元素
  const renderTeacherBoard = () => {
    return (
      <div>
        <Title style={{ textAlign: 'center' }}>个人评教结果查询</Title>
        <Row>
          <Col>
            <Tag>院系: {props.user.department}</Tag>
          </Col>
          <Col>
            <Tag>教师: {props.user.name}</Tag>
          </Col>
          <Col>
            <Tag>编号: {props.user.number}</Tag>
          </Col>
          <Col>
            <Tag>职称: {props.user.academicTitle}</Tag>
          </Col>
        </Row>
        <Row style={{ marginTop: '25px' }}>
          <Col span={4}>
            <Select
              placeholder="学年"
              style={{ width: '100%' }}
              onChange={(value) => {
                if (value) setSchoolYear(`${value}`);
              }}
              allowClear={true}
            >
              {(() => {
                const result = [];
                for (let i = 0; i < schoolYears.length - 1; ) {
                  result.push(`${schoolYears[i]}-${schoolYears[i + 1]}`);
                  i += 1;
                }
                return result;
              })().map((item, index) => (
                <Option key={index} value={item}>
                  {item}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={4} offset={2}>
            <Select
              placeholder="学期"
              style={{ width: '100%' }}
              onChange={(value) => {
                if (value) setSemester(`${value}`);
              }}
              allowClear={true}
            >
              {semesters.map((item, index) => (
                <Option key={index} value={formatSemester(item)}>
                  {formatSemester(item)}
                </Option>
              ))}
            </Select>
          </Col>
        </Row>
        <Row style={{ marginTop: 25 }}>
          <Col>
            <Button
              type="primary"
              onClick={async () => {
                if (schoolYear && semester) {
                  const $teachingEvaluationResult: any = await getTeacherTeachingEvaluationResult({
                    name: props.user.name,
                    number: props.user.number,
                    department: props.user.department,
                    schoolYear,
                    semester,
                  });
                  setTeachingEvaluationResult($teachingEvaluationResult.results);
                  setSyntheticalEvaluate($teachingEvaluationResult.syntheticalEvaluate);
                  setIsModalVisible(true);
                } else {
                  notification.warning({
                    message: '数据未填充完毕',
                    description: '请将所有的表单填写完整',
                  });
                }
              }}
            >
              查询
            </Button>
          </Col>
        </Row>
      </div>
    );
  };

  // 渲染院系角色才能看见的元素
  const renderCollegesBoard = () => {
    return (
      <div>
        <Title style={{ textAlign: 'center' }}>院系评教结果统计</Title>
        <Row>
          <Col>
            <Tag>院系: 电信系</Tag>
          </Col>
        </Row>
        <Row
          style={{
            marginTop: 25,
          }}
        >
          <Col span={4}>
            <Select
              placeholder="学年"
              style={{ width: '100%' }}
              onChange={(value) => {
                if (value) setSchoolYear(`${value}`);
              }}
              allowClear={true}
            >
              {(() => {
                const result = [];
                for (let i = 0; i < schoolYears.length - 1; ) {
                  result.push(`${schoolYears[i]}-${schoolYears[i + 1]}`);
                  i += 1;
                }
                return result;
              })().map((item, index) => (
                <Option key={index} value={item}>
                  {item}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={4} offset={2}>
            <Select
              placeholder="学期"
              style={{ width: '100%' }}
              onChange={(value) => {
                if (value) setSemester(`${value}`);
              }}
              allowClear={true}
            >
              {semesters.map((item, index) => (
                <Option key={index} value={formatSemester(item)}>
                  {formatSemester(item)}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={4} offset={2}>
            <Button
              type="primary"
              icon={<SearchOutlined />}
              onClick={async () => {
                // 发送请求
                if (schoolYear && semester) {
                  const result: any = await getCollegesResult({
                    semester,
                    schoolYear,
                  });
                  setCollegesResultData(result.data);
                } else {
                  notification.warning({
                    message: '数据未填充完毕',
                    description: '请将所有的表单填写完整',
                  });
                }
              }}
            >
              查询
            </Button>
          </Col>
        </Row>
        <Row
          style={{
            marginTop: 25,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          {collegesResultData.length ? (
            <Table
              dataSource={collegesResultData}
              columns={collegesColumns}
              style={{
                width: '100%',
              }}
            />
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
        </Row>
        <Row>
          <Space>
            <Col
              style={{
                marginTop: 25,
              }}
            >
              <Button
                disabled={!collegesResultData.length}
                icon={<ExportOutlined />}
                type="primary"
                onClick={() => {
                  setDownloaded(true);
                  new Promise((resolve, reject) => {
                    try {
                      const tHeader = (collegesColumns || []).map((item) => item.title);
                      const copyCollegesData = [...collegesResultData];
                      const tBody = (copyCollegesData || []).map((item) => {
                        const keys = Object.keys(item);
                        const values = Object.values(item);
                        values.splice(keys.indexOf('key'), 1);
                        return values;
                      });
                      const aoa = [tHeader, ...tBody];
                      const workSheet = xlsxUtils.aoa_to_sheet(aoa);
                      const workBook: WorkBook = xlsxUtils.book_new();
                      xlsxUtils.book_append_sheet(workBook, workSheet, 'Sheet1');
                      const res = writeFile(workBook, '院系评教结果统计.xlsx');
                      resolve(res);
                    } catch (e) {
                      reject(e);
                    }
                  })
                    .then(() => {
                      setDownloaded(false);
                      message.success('导出成功: 院系评教结果统计.xlsx');
                    })
                    .catch((error) => {
                      console.log(error);
                      message.error(`导出失败: 
                    具体原因如下 :
                    ${error}
                  `);
                    });
                }}
              >
                导出
              </Button>
            </Col>
          </Space>
        </Row>
      </div>
    );
  };

  const renderLoading = () => {
    let element = <></>;
    if (!isLoading && props.user.currentAuthority !== 'colleges') {
      element = renderTeacherBoard();
    } else {
      element = renderCollegesBoard();
    }
    if (isLoading) {
      element = <Skeleton active />;
    }
    return element;
  };

  return (
    <PageContainer waterMarkProps={{ content: '河北交通职业技术学院' }}>
      <Card style={{ minHeight: 340 }}>
        <Spin spinning={downloaded} delay={500}>
          {renderLoading()}
        </Spin>
        <Modal
          title="个人教学评教查询结果"
          visible={isModalVisible}
          onOk={() => {
            setIsModalVisible(false);
          }}
          onCancel={() => {
            setIsModalVisible(false);
          }}
        >
          <Row>
            <Col>
              <Tag>院系: {props.user.department}</Tag>
            </Col>
            <Col>
              <Tag>教师: {props.user.name}</Tag>
            </Col>
            <Col>
              <Tag>编号: {props.user.number}</Tag>
            </Col>
            <Col>
              <Tag>职称: {props.user.academicTitle}</Tag>
            </Col>
          </Row>
          <Row
            style={{
              marginTop: 25,
            }}
          >
            <Col>
              {teachingEvaluationResult.length ? (
                <Table columns={teacherColumns} dataSource={teachingEvaluationResult} />
              ) : null}
            </Col>
          </Row>
          <Row>
            <Col>综合评价 :</Col>
          </Row>
          {Object.keys(syntheticalEvaluate).length ? (
            <Row
              style={{
                marginTop: 25,
              }}
            >
              <Col>
                <Tag>平均分: {syntheticalEvaluate.average}</Tag>
              </Col>
              <Col>
                <Tag>院系排名: {syntheticalEvaluate.collegesRank}</Tag>
              </Col>
              <Col>
                <Tag>评价结果: {syntheticalEvaluate.evaluateResult}</Tag>
              </Col>
            </Row>
          ) : null}
        </Modal>
      </Card>
    </PageContainer>
  );
};

const mapStateFromProps = ({ user }: ConnectState): IResultQueryInterface => ({
  user: user.currentUser as CurrentUser,
});

export default connect(mapStateFromProps)(ResultQuery);
